<template>
  <el-button text :bg="isShow" :type="isShow ? 'primary' : ''" @click="handleShow">
    事件更新
  </el-button>
  <div id="popup" class="ol-popup" v-show="coordinate" ref="container">
    <div class="popup-top">
      事件详细信息
      <div id="popup-closer" class="ol-popup-closer" @click="Close" ref="closer"></div>
    </div>

    <div id="popup-content">
      <el-form
        ref="ruleFormRef"
        style="max-width: 380px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-position="left"
        label-width="70px"
        size="small"
      >
        <el-form-item label="事件编号" prop="number" style="width: 250px">
          <el-input v-model="ruleForm.number" autocomplete="off" placeholder="如:js202401010001" />
        </el-form-item>
        <el-form-item label="事件类型" prop="type" style="width: 250px">
          <el-select v-model="ruleForm.type" placeholder="Select">
            <el-option v-for="item in types" :key="item.value" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="事件等级" prop="grade" style="width: 250px">
          <el-select v-model="ruleForm.grade" placeholder="Select">
            <el-option
              v-for="item in grades"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="date" style="width: 250px">
          <el-date-picker
            v-model="ruleForm.date"
            type="datetime"
            placeholder="Select date and time"
          />
        </el-form-item>
        <el-form-item label="发生地点" prop="position" style="width: 250px">
          <el-input
            v-model="ruleForm.position"
            autocomplete="off"
            placeholder="如:武汉市光谷广场"
          />
        </el-form-item>
        <el-form-item label="车牌号" prop="carnumber" style="width: 250px">
          <el-input v-model="ruleForm.carnumber" autocomplete="off" placeholder="如:鄂A00001" />
        </el-form-item>
        <el-form-item label="驾驶员" prop="person" style="width: 250px">
          <el-input v-model="ruleForm.person" autocomplete="off" placeholder="如:张三" />
        </el-form-item>
        <el-form-item label="处理状态" prop="status" style="width: 250px">
          <el-select v-model="ruleForm.status" placeholder="Select">
            <el-option
              v-for="item in statuses"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <div class="move">
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)" color="#0993ff">
              提交
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessageBox } from 'element-plus'
let popup, OID, center
const { map } = defineProps({
  map: {
    type: Object,
    required: true,
  },
})

const wsmLayer = map.getLayers().item(2) //获取瓦片图层
const wsmSource = wsmLayer.getSource() //获取瓦片图层数据源

const isShow = ref(false)
const container = ref(null)
const closer = ref(null)
const coordinate = ref('')
const ruleFormRef = ref()
const ruleForm = reactive({
  number: '',
  type: '',
  grade: '',
  date: '',
  position: '',
  carnumber: '',
  person: '',
  status: '',
})
const types = [
  { value: '碰撞' },
  { value: '刮蹭' },
  { value: '碾压' },
  { value: '追尾' },
  { value: '超车' },
  { value: '失火' },
  { value: '其他' },
]
const grades = [
  { value: 1, label: '轻微事故' },
  { value: 2, label: '一般事故' },
  { value: 3, label: '严重事故' },
  { value: 4, label: '灾难事故' },
]
const statuses = [
  { value: 0, label: '待处理' },
  { value: 1, label: '处理中' },
  { value: 2, label: '已归档' },
]

const rules = reactive({
  number: [{ required: true, trigger: 'blur' }],
  type: [{ required: true, trigger: 'blur' }],
  grade: [{ required: true, trigger: 'blur' }],
  date: [{ required: true, trigger: 'blur' }],
  position: [{ required: true, trigger: 'blur' }],
  carnumber: [{ required: true, trigger: 'blur' }],
  person: [{ required: true, trigger: 'blur' }],
  status: [{ required: true, trigger: 'blur' }],
})
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    //使用 validate 对整个表单进行校验 回调函数返回值valid 为true时代表校验通过，false代表校验不通过。
    if (valid) {
      updateEvent()
      ElMessageBox.alert('提交成功', {
        type: 'success',
      })
      Close()
      resetForm(formEl)
      console.log('submit!')
    } else {
      console.log('error submit!')
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
const handleShow = () => {
  isShow.value = !isShow.value
  if (!isShow.value) {
    Close()
  }
}
onMounted(() => {})
function Close() {
  //未定义popup位置

  popup?.setPosition(undefined)
  //失去焦点
  closer.value.blur()
  return false
}

map.on('click', function (e) {
  if (!isShow.value) return
  coordinate.value = e.coordinate
  getEvent()
})
function getEvent() {
  //初始化查询结构对象，设置查询结构包含几何信息
  var queryStruct = new Zondy.Service.QueryFeatureStruct()
  //是否包含几何图形信息
  queryStruct.IncludeGeometry = true
  //是否包含属性信息
  queryStruct.IncludeAttribute = true
  //是否包含图形显示参数
  queryStruct.IncludeWebGraphic = false
  var rule = new Zondy.Service.QueryFeatureRule({
    //是否将要素的可见性计算在内
    EnableDisplayCondition: false,
    //是否完全包含
    MustInside: false,
    //是否仅比较要素的外包矩形
    CompareRectOnly: false,
    //是否相交
    Intersect: true,
  })
  //创建一个用于查询的点形状
  var pointObj = new Zondy.Object.Point2D(coordinate.value[0], coordinate.value[1])
  //设置查询点的搜索半径
  pointObj.nearDis = 0.0005

  //实例化查询参数对象
  var queryParam = new Zondy.Service.QueryByLayerParameter('gdbp://MapGisLocal/wuhan/sfcls/事件', {
    geometry: pointObj,
    resultFormat: 'json',
    struct: queryStruct,
    rule: rule,
  })
  //设置查询分页号
  queryParam.pageIndex = 0
  //设置查询要素数目
  queryParam.recordNumber = 100
  var queryService = new Zondy.Service.QueryLayerFeature(queryParam, {
    ip: '127.0.0.1',
    port: '8089', //访问IGServer的端口号，.net版为6163，Java版为8089
  })
  //执行查询操作，querySuccess为查询回调函数
  queryService.query(querySuccess, queryError)
}
//查询失败回调
function queryError(e) {
  //停止进度条
  console.log(e)
}
//查询成功回调
function querySuccess(result) {
  //初始化Zondy.Format.PolygonJSON类
  var format = new Zondy.Format.PolygonJSON()
  //将MapGIS要素JSON反序列化为ol.Feature类型数组
  var features = format.read(result)
  if (features) {
    ruleForm.number = features[0].getProperties().get('事件编号')
    ruleForm.type = features[0].getProperties().get('事件类型')
    ruleForm.grade = parseInt(features[0].getProperties().get('事件等级'))
    ruleForm.date = features[0].getProperties().get('发生时间')
    ruleForm.position = features[0].getProperties().get('发生地点')
    ruleForm.carnumber = features[0].getProperties().get('车牌号')
    ruleForm.person = features[0].getProperties().get('驾驶员')
    ruleForm.status = parseInt(features[0].getProperties().get('处理状态'))
    OID = features[0].getId()
    center = features[0].getGeometry().flatCoordinates
    openOverlay()
  } else {
    Close()
    OID = null
    center = null
  }
}
function openOverlay() {
  popup = new ol.Overlay({
    //要转换成overlay的HTML元素
    element: container.value,
    //当前窗口可见
    autoPan: true,
    //Popup放置的位置
    positioning: 'bottom-center',
    //是否应该停止事件传播到地图窗口
    stopEvent: true,
    autoPanAnimation: {
      //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
      duration: 250,
    },
  })
  map.addOverlay(popup)
  popup.setPosition(center)
}
function updateEvent() {
  //设置当前点要素的几何信息
  const pntObj = new Zondy.Object.GPoint(center[0], center[1])
  const featureGeom = new Zondy.Object.FeatureGeometry({
    PntGeom: [pntObj],
  })
  console.log(OID)

  const attValue = [
    ruleForm.number,
    ruleForm.type,
    ruleForm.grade,
    ruleForm.date,
    ruleForm.position,
    ruleForm.carnumber,
    ruleForm.person,
    ruleForm.status,
  ]
  let colorNum
  switch (ruleForm.status) {
    case 0:
      colorNum = 6
      break
    case 1:
      colorNum = 4
      break
    case 2:
      colorNum = 90
      break
    default:
      break
  }

  //描述点要素的符号参数信息
  const cPntInfo = new Zondy.Object.CPointInfo({
    Angle: 0,
    Color: colorNum,
    SymHeight: 5,
    SymID: 21,
    SymWidth: 5,
  })
  //设置当前点要素的图形参数信息
  const graphic = new Zondy.Object.WebGraphicsInfo({
    InfoType: 1,
    PntInfo: cPntInfo,
  })
  const feature1 = new Zondy.Object.Feature({
    fGeom: featureGeom,
    GraphicInfo: graphic,
    AttValue: attValue,
    feature: 1,
  })
  //   feature1.setFType(1)
  feature1.setFID(OID)
  const cAttStruct = new Zondy.Object.CAttStruct({
    FldName: [
      '事件编号',
      '事件类型',
      '事件等级',
      '发生时间',
      '发生地点',
      '车牌号',
      '驾驶员',
      '处理状态',
    ],
    FldNumber: 8,
    FldType: ['string', 'string', 'short', 'string', 'string', 'string', 'string', 'short'],
  })
  //创建一个要素数据集
  const featureSet = new Zondy.Object.FeatureSet({
    AttStruct: cAttStruct,
    SFEleArray: [feature1],
  })
  var editService = new Zondy.Service.EditLayerFeature('gdbp://MapGisLocal/wuhan/sfcls/事件', {
    ip: '127.0.0.1',
    port: '8089',
  })
  editService.update(featureSet, onPntSuccess)
}

function onPntSuccess(data) {
  console.log(data)
  // 尝试刷新地图
  wsmSource.updateParams({
    // A: Math.random(),
    // map根据params查找缓存, 查不到就刷新,建立新缓存
    TIME: new Date().getTime(), //唯一性标识, 用于map区分params, 强制刷新缓存, 可以是任意无关属性名和值
  })
}
</script>

<style scoped>
.ol-popup {
  width: 300px;
  height: 400px;
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 5px;
  left: -50px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  position: absolute;
  top: 5px;
  right: 5px;
}

.ol-popup-closer:after {
  content: '✖';
}

#popup-content {
  position: absolute;
  top: 40px;
  font-size: 14px;
  font-family: '微软雅黑';
}

#popup-content .markerInfo {
  font-weight: bold;
}

.popup-top {
  position: absolute;
  background-color: #0994ff;
  color: #fff;
  padding: 5px;
  top: 0px;
  left: 0px;
  width: 300px;
  border-radius: 10px 10px 0 0;
}
.move {
  position: absolute;
  bottom: -35px;
}
</style>
